<template>
  <view class="container">
    <!-- 卡片式翻动区域 -->
	<view >
		<u-modal :show="showShare" title="恭喜,您已经完成了,赶紧分享给朋友吧" 
		closeOnClickOverlay=true
		showCancelButton
		  @confirm="onConfirm"
		 >
		<image src="/static/img/gold.png">
		</u-modal>
		
	</view>
    <view 
      class="card-container" 
      :style="{ transform: `translateX(-${currentIndex * 100}%)` }"
    >
      <view 
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        class="card-item" 
        v-for="(card, index) in cards" 
        :key="index"
      >
        <view class="card-content">
          <button class="buttontop-indicator" @touchstart.stop="setAll" >设置</button>
          <button class="buttontop1-indicator" @touchstart.stop="toggleTranslate">{{ translateButtonLabel }}</button>
          <button class="buttontop2-indicator" @touchstart.stop="shared">分享</button>
        	
          <!-- 使用固定的本地图片 -->
          <image :src="card.image? card.image : require('@/static/img/yes.png')" class="card-image"></image>
          	<u-line-progress :percentage="process"  class="card-image" activeColor="blue"/>
			<u-tag text="已完成" type="success" shape="circle" class="card-image" :show="pageOver"></u-tag>
          <!-- 内容显示在图片下方 -->
          <view class="">
            <block v-for="(part, partIndex) in splitContent(card.content)" :key="partIndex">
              <text 
                @touchstart.stop 
                class="clickable-part" 
                @click="showWordDetail(part)"
                :style="{ 
                  marginRight: '10px', 
                  color: activePart === part ? 'red' : currentColor 
                }"
              >
                {{ part }}
              </text>
            </block>
          </view>
          
          <view v-if="isTranslated" class="">
            <u--text :text="china"
              block
              size='23'
              style="position: relative;bottom: 1px;">
            </u--text>
          </view>
        </view>
		  
      </view>
    </view>
    
    <!-- 当前页码显示 -->
	
	
    <view class="page-indicator" @touchstart.stop >
      <text>当前页: {{ currentIndex + 1 }} / {{ cards.length }}</text>
    </view>
    
    <view>
      <button class="button-indicator" @click="handleLeftButtonClick" >播放</button>
      <button class="button1-indicator" @click="handleCenterButtonClick" >{{ isRecording ? '结束' : '录音' }}</button>
      <button class="button2-indicator" @click="handleRightButtonClick" :disabled="tempclick">放音</button>
    </view>
	<u-popup :show="isTableVisible" :round="10" mode="top" closeOnClickOverlay @close="closePopup" class="custom-popup">
		<view class="popup-content">
			<view class="popup-header">
				<text class="popup-title">{{ currentWord }}</text>
				<view class="popup-button-container">
					<button class="popup-button" @click.stop="addToWordBook">加入生词本</button>
					<button class="popup-button" @click.stop="openWordBook">打开生词本</button>
				</view>
			</view>
			<view class="popup-body">
				<view class="phonetic-section">
					<view class="phonetic-item">
						<text class="flag">🇺🇸</text>
						<text class="phonetic-text">[{{ currentPhonetic.us }}]</text>
						<button class="pronounce-button" @click="pronounceWord(0)">美式发音</button>
					</view>
					<view class="phonetic-item">
						<text class="flag">🇬🇧</text>
						<text class="phonetic-text">[{{ currentPhonetic.uk }}]</text>
						<button class="pronounce-button" @click="pronounceWord(1)">英式发音</button>
					</view>
				</view>
				<view class="explanation-section">
					<text class="explanation-text">{{ currentExplanation }}</text>
				</view>
				<view class="example-section">
					<view class="example-header">
						<text class="example-label">例句</text>
						<button class="example-button">收藏例句</button>
					</view>
					<text class="example-text">{{ currentContent }}</text>
				</view>
			</view>
		</view>
	</u-popup>
  </view>
</template>

<script>
import { voicePlay } from '@/tools/voice.js';
import { sendGetRequest } from '@/tools/translate.js';

export default {
  data() {
    return {
		//完成的弹窗
		showShare:false,
		//临时点击
		tempclick:true,
		//设置一个数组用于记录录音次数
		timeOnSpeak:[],
		//进度
		process:0,
		pageOver:false,
      currentColor: 'black', // 默认颜色为黑色
      activePart: null, // 记录当前被点击的子字符串
      currentWord: '', // 当前单词
      currentPhonetic: { us: '', uk: '' }, // 当前单词的音标
      currentExplanation: '', // 当前单词的释义
      currentExample: '', // 当前单词的例句
      isTableVisible: false, // 控制表格的显示状态
      china: '',
      isRecording: false,
      hasRecorded: false,
      recorderManager: null,
      innerAudioContext: null,
      tempFilePath: '',
      currentIndex: 0, // 初始化 currentIndex
      cards: [], // 初始化 cards
      startX: 0,
      moveX: 0,
      threshold: 50,
      currentContent: '', // 当前卡片的content
      isMouseDown: false, // 鼠标是否按下
      mouseStartX: 0, // 鼠标按下时的初始X坐标
      mouseMoveX: 0, // 鼠标移动时的X坐标
      isTranslated: false, // 控制china显示的开关
      touchStartTime: 0, // 触摸开始时间
      touchEndTime: 0, // 触摸结束时间
    };
  },
  onLoad(options) {
    if (options) {
      this.searchname = options.name;
      this.loadTailData(this.searchname);
    } else {
      uni.showToast({
        title: '未接收到name参数',
        icon: 'none',
        duration: 1000
      });
    }
    this.recorderManager = uni.getRecorderManager();
    this.innerAudioContext = uni.createInnerAudioContext();

    this.recorderManager.onStart(() => {
      console.log('开始录音');
    });

    this.recorderManager.onStop((res) => {
      console.log('录音停止', res.tempFilePath);
      this.tempFilePath = res.tempFilePath;
      this.hasRecorded = true;
      this.isRecording = false;
    });

    this.recorderManager.onError((err) => {
      console.error('录音出错', err);
    });

    this.innerAudioContext.onError((err) => {
      console.error('播放出错', err);
    });
  },
  mounted() {
    voicePlay(this.currentContent);
	for(var n = 0; n < 100; n++) this.timeOnSpeak[n] = 0
  },

  methods: {
	  //分享给朋友
	  onConfirm(){
		 console.log("111111111") 
	  },
    // 翻译
    setAll() {
		uni.showToast({
		  title: '等待后期升级',
		  icon:"none"
		});
    },
    shared() {
		this.showShare =true;
 if (this.timeOnSpeak.reduce((acc, num) => acc + num, 0) == 3*this.cards.length)
 {
	this.showShare =true;
 }

    },

    async translate() {
      try {
        const result = await sendGetRequest(this.currentContent);
        this.china = result;
      } catch (error) {
        console.error('翻译出错:', error);
      }
    },
    // 获取内容数据
    loadTailData(name) {
      uni.request({
        header: {
          'Content-Type': 'application/json'  // 设置请求头，指定请求体的格式
        },
        url: getApp().globalData.baseUrl + "getAllDrawtailByName", // 拼接完整的接口地址
        method: 'POST', // 请求方法
        data: {
          name: name // 传递name参数
        },
        dataType: 'json', // 指定返回的数据类型
        success: (res) => {
          if (res.data.code === 0) {
            this.cards = res.data.data; // 将后端返回的数据存储到cards数组中
            if (this.cards.length > 0) {
              this.currentContent = this.cards[this.currentIndex].content;
			  for (var i = 0; i < this.currentIndex.length; i++) {
			  	this.timeOnSpeak[i] = 0;
			  }
			  console.log(this.timeOnSpeak[this.currentIndex])
            }
          } else {
            uni.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 1000
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none',
            duration: 1000
          });
        }
      });
    },
	//页数设置清空
	clearIndex(index){
		if(this.timeOnSpeak[index] <3 ||this.timeOnSpeak[index]==null){
			this.pageOver =false;
			if(this.timeOnSpeak[index]>=0  &&this.timeOnSpeak[index]<3){
				this.process =this.timeOnSpeak[index] *33;
			}
			
		}else{
			this.process =100;
			this.pageOver =true;
		}
		

	},
    prevPage() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
        this.currentContent = this.cards[this.currentIndex].content;
		this.clearIndex(this.currentIndex);
      }
    },
    nextPage() {
      if (this.currentIndex < this.cards.length - 1) {
        this.currentIndex++;
        this.currentContent = this.cards[this.currentIndex].content;
		this.clearIndex(this.currentIndex);
      }
    },
    handleTouchStart(event) {
      this.startX = event.touches[0].clientX;
      this.touchStartTime = Date.now();
    },
    handleTouchMove(event) {
      this.moveX = event.touches[0].clientX;
    },
    handleTouchEnd() {
      const distance = this.startX - this.moveX;
      const touchDuration = Date.now() - this.touchStartTime;
      
      // 如果滑动距离大于阈值且触摸时间较短，认为是滑动操作
      if (Math.abs(distance) > this.threshold && touchDuration < 300) {
        if (distance > 0) {
          // 向左滑动
          this.isTranslated = false;
          this.nextPage();
        } else {
          // 向右滑动
          this.prevPage();
          this.isTranslated = false;
        }
      } else {
        // 否则认为是点击操作
        this.handleCardClick();
      }
    },
    handleCardClick() {
      // 在这里处理卡片的点击逻辑
    },
    handleLeftButtonClick() {
      console.log('左按钮点击', this.currentContent);
      voicePlay(this.currentContent, 1);
      this.currentColor = 'green'; // 播放后变为绿色
    },
    handleCenterButtonClick() {
      console.log('中间按钮点击', this.currentContent);
      if (this.isRecording) {
        this.recorderManager.stop();
      } else {
        this.recorderManager.start();
        this.isRecording = true;
		this.tempclick =false;
      }
    },
	//放音事件
  handleRightButtonClick() {
      if (this.hasRecorded) {
		  this.tempclick = true;
          this.innerAudioContext.src = this.tempFilePath;
          this.innerAudioContext.play();
  
          this.process += 33;
          this.timeOnSpeak[this.currentIndex] += 1;
  
          if (this.process >= 99) {
              this.pageOver = true;
              this.process = 100;
              this.timeOnSpeak[this.currentIndex] = 3;
          }
  
         // 监听音频播放结束事件
          this.innerAudioContext.onEnded(() => {
              this.tempFilePath = ''; // 清空录音文件路径
              this.hasRecorded = false; // 标记为未录制
			  
          });
  
      } else {
          uni.showToast({
              title: '请先结束录音或检查是否录音',
              icon: 'none'
          });
      }
  },
    splitContent(content) {
      // 将字符串按非连续空白分割
      return content.split(/\s+/);
    },
    
    toggleTranslate() {
      // 切换china显示开关
      if (!this.isTranslated) {
        this.translate();
      }
      this.isTranslated = !this.isTranslated;
    },
    showWordDetail(word) {
      this.currentWord = word;
      this.currentPhonetic = this.getPhonetic(word); // 获取音标
      this.getWordMeaning(word); // 获取单词意思
      // 显示弹出框
      this.isTableVisible = true;
      // 点击单词变红
      this.activePart = word;
    },
    closePopup() {
      // 关闭弹出框
      this.isTableVisible = false;
      // 关闭弹窗时恢复单词颜色
      this.activePart = null;
    },
    pronounceWord(type) {
      // 使用voicePlay实现单词发音
      voicePlay(this.currentWord, type);
    },
    getPhonetic(word) {
      // 获取单词的音标，这里可以调用API或从本地数据获取
      return { us: 'pəˈnɛləpi', uk: 'pəˈnɛləpi' };
    },
    async getWordMeaning(word) {
      try {
        const result = await sendGetRequest(word);
        this.currentExplanation = result;
        this.currentExample = ''; // 如果需要例句，也可以在这里处理
      } catch (error) {
        console.error('获取单词意思出错:', error);
        this.currentExplanation = '未能获取单词意思';
        this.currentExample = '';
      }
    },
    addToWordBook() {
      uni.showToast({
        title: '已加入生词本',
        icon: 'success',
        duration: 1000
      });
    },
    openWordBook() {
      uni.showToast({
        title: '打开生词本',
        icon: 'none',
        duration: 1000
      });
    }
  },
  computed: {
    translateButtonLabel() {
      return this.isTranslated ? '翻译' : '翻译';
    }
  }
};
</script>

<style scoped>
.container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.card-container {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px); /* 为底部按钮留出空间 */
  transition: transform 0.3s ease-in-out;
  perspective: 1000px;
  cursor: grab; /* 添加鼠标样式，表示可以拖动 */
}

.card-item {
  flex: 0 0 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  transform-style: preserve-3d;
}

.card-content {
  width: 90%;
  height: 80%;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  position: relative;
}

.card-image {
  width: 90%;
  height: 50%;
  object-fit: cover;
  border-radius: 10px;
  margin-bottom: 15px;
}

.card-text {
  font-size: 18px;
  font-family: 'Lucida Sans';
  color: #333;
  line-height: 1.6;
  text-align: left;
  margin-bottom: 20px;
  padding: 0 20px;
}

.page-indicator {
  position: fixed;
  bottom: 90px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  z-index: 10;
}

.button-indicator {
  position: fixed;
  bottom: 30px;
  left: 20%;
  transform: translateX(-50%);
  background-color: #4CAF50;
  color: black;
  border: none;
  border-radius: 20px;
  z-index: 10;
  padding: 8px 16px;
  cursor: pointer;
}

.button1-indicator {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #2196F3;
  color: black;
  border: none;
  border-radius: 20px;
  z-index: 10;
  padding: 8px 16px;
  cursor: pointer;
}

.button2-indicator {
  position: fixed;
  bottom: 30px;
  left: 80%;
  transform: translateX(-50%);
  background-color: #FF9800;
  color: black;
  border: none;
  border-radius: 20px;
  z-index: 10;
  padding: 8px 16px;
  cursor: pointer;
}
.buttontop-indicator{
	border-radius: 10rpx;
	position: fixed;
	top: 1px;
	left: 40%;
}
.buttontop1-indicator{
	position: fixed;
	top: 1px;
	left: 60%;
}
.buttontop2-indicator{
	position: fixed;
	top: 1px;
	left: 80%;
}

.clickable-part {
  font-size: 33px;
  font-weight: bold;
}

/* Popup样式 */
.custom-popup /deep/ .u-popup__content {
  background-color: #fef9e7 !important;
  border: 2px solid #e0b85f !important;
  border-radius: 10px !important;
  width: 80% !important;
  left: 10% !important;
}

.popup-content {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #fef9e7;
  border-bottom: 1px solid #e0b85f;
}

.popup-title {
  font-size: 24px;
  font-weight: bold;
  color: #5d4112;
}

.popup-button-container {
  display: flex;
}

.popup-button {
  background-color: #ffffff;
  color: #5d4112;
  border: 1px solid #e0b85f;
  border-radius: 5px;
  padding: 5px 10px;
  margin-left: 10px;
  font-size: 14px;
}

.phonetic-section {
  padding: 10px;
  background-color: #fef9e7;
  border-bottom: 1px solid #e0b85f;
  display: flex;
  justify-content: space-between;
}

.phonetic-item {

}

.flag {
  margin-right: 5px;
  font-size: 18px;
}

.phonetic-text {
  font-family: Arial, sans-serif;
  font-size: 18px;
  color: #5d4112;
}

.pronounce-button {
  background-color: #ffffff;
  color: #5d4112;
  border: 1px solid #e0b85f;
  border-radius: 5px;
  padding: 5px 10px;
  font-size: 14px;
}

.explanation-section {
  padding: 10px;
  background-color: #fef9e7;
  border-bottom: 1px solid #e0b85f;
}

.explanation-text {
  line-height: 1.6;
  color: #5d4112;
  font-size: 16px;
}

.example-section {
  padding: 10px;
  background-color: #fef9e7;
}

.example-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.example-label {
  background-color: #f5f5dc;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  color: #5d4112;
}

.example-button {
  background-color: #f5f5dc;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  font-size: 14px;
  color: #5d4112;
}

.example-text {
  margin-top: 10px;
  line-height: 1.6;
  color: #5d4112;
  font-size: 16px;
}
</style>